package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * rabbitmq队列生产者入门程序
 */
public class Producer01 {
    private static final String QUEUE_NAME = "helloWorld";

    public static void main(String[] args) {
        // 通过链接工程创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        try {
            // 建立新的链接
            connection = connectionFactory.newConnection();
            // 建立会话通道, 所有的请求都是在通道完成的,通道之间相互独立
            Channel channel = connection.createChannel();
            // 声明队列
            //queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            // 创建消息
            String message = "Hello World!";
            // 发送消息
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println(" [√] Sent '" + message + "'");
            connection.close();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {

        }

    }
}
